<template>
  <ul class="list">
    <!-- 定义touch事件 start  move   end -->
    <li
      class="item"
      v-for="item of letters"
      :key="item" :ref="item"
      @touchstart.prevent="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @click="handleClick"
    >
    {{item}}
    </li>
  </ul>
</template>
<script>
export default {
  name: 'CityAlphabet',
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    return {
      // 触控状态初始值
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  // 重新渲染后执行-性能优化
  updated () {
    // 获取dom元素A距离顶部距离
    this.startY = this.$refs['A'][0].offsetTop
  },
  props: {
    cities: Object
  },
  methods: {
    // 子组件传值给父组件   发布订阅模式  选择值：A、B、C
    handleClick (e) {
      this.$emit('change', e.target.innerText)
    },
    // 触控开始，状态标记为true
    handleTouchStart () {
      this.touchStatus = true
    },
    // 触控经过效果
    handleTouchMove (e) {
      // 判断当前状态
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        // 函数节流-性能优化
        this.timer = setTimeout(() => {
          // 获取触控点距离顶部距离差值
          const touchY = e.touches[0].clientY - 79
          // 获取触控的节点下标 取整
          const index = Math.floor((touchY - this.startY) / 20)
          if (index >= 0 && index < this.letters.length) {
            // 发布订阅模式  出发外部组件函数  滚动外部dom元素到指定位置
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    // 触控结束，状态标记为false
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.list
  display flex
  flex-direction column
  justify-content center
  position absolute
  top 1.58rem
  right 0
  bottom 0
  width .4rem
  .item
    text-align center
    line-height .4rem
    color $bgColor
</style>
